//
//  QKReuseTableView.m
//  testTool
//
//  Created by Su on 2018/12/9.
//  Copyright © 2018 com.qiankun. All rights reserved.
//

#import "QKReuseTableView.h"
#import "QKReusePool.h"

@interface QKReuseTableView ()
{
    UIView *containerView;
    QKReusePool *reusePool;
}

@end
@implementation QKReuseTableView

-(void)reloadData{
    [super reloadData];
    
    if (containerView == nil) {
        containerView = [[UIView alloc] init];
        containerView.backgroundColor = UIColor.whiteColor;
        [self.superview insertSubview:containerView aboveSubview:self];
    }
    if (reusePool == nil) {
        reusePool = [[QKReusePool alloc] init];
    }
    [reusePool reset];
//    reload 索引条
    [self reloadIndexTitle];
}

-(void)reloadIndexTitle{
    
//    设置一个title数组
    NSArray <NSString *> * titleArray  = nil;
    
    if ([self.indexDataSource respondsToSelector:@selector(indexTitleFromReuseTable:)]) {
        titleArray = [self.indexDataSource indexTitleFromReuseTable:self];
    }
    
    if (!titleArray || titleArray.count<=0) {
        [containerView setHidden:YES];
        return;
    }


    NSUInteger count = titleArray.count;
    CGFloat btnWidth = 60;
    CGFloat btnHeight = self.frame.size.height/count;
    
    for (int i = 0; i< count; i++) {
        
        NSString *title = [titleArray objectAtIndex:i];
        UIButton *btn = (UIButton *)[reusePool getReuseTableView];
        
        if (btn == nil) {
            btn = [[UIButton alloc] initWithFrame:CGRectZero];
            btn.backgroundColor = UIColor.whiteColor;
            [reusePool addViewForReusePool:btn];
            NSLog(@"creat  a  btn");
        }else{
            NSLog(@"reuse button");
        }
        
        [containerView addSubview:btn];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn  setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [btn setFrame:CGRectMake(0, i*btnHeight, btnWidth, btnHeight)];
    }
    
    [containerView setHidden:NO];
    containerView.frame = CGRectMake(self.frame.origin.x + self.frame.size.width - btnWidth, self.frame.origin.y, btnWidth, self.frame.size.height);
    
}


@end
